package initialize

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"net"
	"net/http"
	"os"
	"os/exec"
	"svs/config"
	"svs/global"
	"svs/middleware"
	"time"
)

type Server struct {
	Host     string
	Port     int64
	Router   *gin.Engine
	Listener net.Listener
}

func NewServer() (*Server, error) {
	s := InitServer(global.CONFIG.Gin)
	server := new(Server)
	server.Host = "0.0.0.0"
	server.Port = 8090 //global.CONFIG.Gin.Port
	server.Router = s
	s.ForwardedByClientIP = true
	return server, nil
}

func InitServer(config config.Gin) *gin.Engine {
	gin.SetMode(config.Mode)
	server := gin.New()
	global.CACHE.Set("runStartTime", time.Now().Unix())
	//允许跨域
	server.Use(middleware.AllowCors())
	//操作日志
	//server.Use(middleware.LogHandle())
	//自定义日志
	InitLogger()
	//初始化路由
	InitRoute(server)

	return server
}

// 监听请求、监听信号
func (server *Server) Start() error {
	if err := server.Listen(); err != nil {
		fmt.Println("失败", err.Error())
		return err
	}
	return nil
}
func (server *Server) Listen() error {

	addr := fmt.Sprintf("%s:%d", server.Host, server.Port)
	httpServer := &http.Server{
		Addr:    addr,
		Handler: server.Router,
	}
	var err error
	server.Listener, err = net.Listen("tcp", httpServer.Addr)
	if err != nil {
		return err
	}
	// 开启服务
	if err := httpServer.Serve(server.Listener); err != nil && err != http.ErrServerClosed {
		//if err := httpServer.ServeTLS(server.Listener, global.CONFIG.Https.PemPath, global.CONFIG.Https.KeyPath); err != nil && err != http.ErrServerClosed {
		err = errors.New(fmt.Sprintf("listen error:%v\n", err))
		return err
	}

	return nil
}

func StripSlice(slice []string, element string) []string {
	for i := 0; i < len(slice); {
		if slice[i] == element && i != len(slice)-1 {
			slice = append(slice[:i], slice[i+1:]...)
		} else if slice[i] == element && i == len(slice)-1 {
			slice = slice[:i]
		} else {
			i++
		}
	}
	return slice
}

func SubProcess(args []string) *exec.Cmd {
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Start()
	if err != nil {
		fmt.Fprintf(os.Stderr, "[-] Error: %s\n", err)
	}
	return cmd
}
